﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using thinger.DataConvertLib;
using xiaoxiong.KYJDAL.MyDbcontext;

namespace xiaoxiong.KYJDAL.Services
{
    public class ActualDataService
    {
        /// <summary>
        /// 实时数据存储
        /// </summary>
        /// <param name="varNameList"></param>
        /// <param name="varValueList"></param>
        /// <returns></returns>
        public OperateResult InsertActual(List<string> varNameList,List<string> varValueList)
        {
            // 参数校验
            if (varNameList == null || varValueList == null)
                return OperateResult.CreateFailResult("参数列表不能为null");
            if (varNameList.Count != varValueList.Count)
                return OperateResult.CreateFailResult("变量名与值数量不一致");
            if (varNameList.Count == 0)
                return OperateResult.CreateFailResult("varNameList 数据为 0");
            // 使用 SqlSugar 动态对象
            var dynamicObj = new Dictionary<string, object>();
            for (int i = 0; i < varNameList.Count; i++)
            {
                var fieldName = varNameList[i];
                // 值类型转换（示例转换逻辑）
                if (double.TryParse(varValueList[i], out double numericValue))
                {
                    dynamicObj[fieldName] = numericValue;
                }
                else
                {
                    dynamicObj[fieldName] = varValueList[i];
                }
            }
            try
            {
                // 获取 SqlSugar 实例（根据实际配置获取）
                using (var context = new kyjDbContext())
                {
                    return OperateResult.CreateSuccessResult(context.Db.Insertable(dynamicObj)
                            .AS("actualdata")  // 指定表名
                            .RemoveDataCache()    // 清除缓存
                            .ExecuteCommand());
                }
            }
            catch(Exception ex)
            {
                return OperateResult.CreateFailResult($"数据插入失败: {ex.Message}");
            }

        }


        public DataTable QueryActualDataByTime(string startTime,string endTime,List<string> columns)
        {
            try
            {
                if (!DateTime.TryParse(startTime, out DateTime start))
                    throw new ArgumentException("Invalid startTime format.");

                if (!DateTime.TryParse(endTime, out DateTime end))
                    throw new ArgumentException("Invalid endTime format.");

                using (var context = new kyjDbContext())
                {
                    // 创建列名的副本，避免修改原始参数
                    var selectedColumns = new List<string>(columns);

                    // 如果未包含时间列，则添加
                    if (!selectedColumns.Any(c => c.Equals("InsertTime", StringComparison.OrdinalIgnoreCase)))
                    {
                        selectedColumns.Insert(0, "InsertTime"); // 插入到首位
                    }

                    // 拼接最终查询列
                    string columnStr = string.Join(",", selectedColumns);

                    return context.Db.Queryable<dynamic>()
                        .AS("actualdata")
                        .Where("InsertTime >= @start AND InsertTime <= @end", new { start, end })
                        .Select(columnStr)
                        .ToDataTable();
                }
            }catch(Exception ex)
            {
                return null;
            }

        }
    
    
    
        /// <summary>
        /// 查询报表数据，根据时间间隔
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="conditions"></param>
        /// <param name="dataTableName"></param>
        /// <returns></returns>
        public DataTable QueryReportDataByCondition(string start,string end,List<string> conditions,string dataTableName)
        {
            try
            {
                // 动态表名上下文
                using(var context = new kyjDbContext())
                {
                    return context.Db.Queryable<object>()
                        .AS("actualdata") // 动态指定表名
                        .Where($"InsertTime BETWEEN @start AND @End", new { start, End = end })
                        .Select(string.Join(",", conditions))
                        .ToDataTable();
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 参数验证
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="tableName"></param>
        /// <exception cref="ArgumentException"></exception>
        private void ValidateInputs(string start, string end, string tableName)
        {
            // 时间格式验证
            if (!DateTime.TryParse(start, out _) || !DateTime.TryParse(end, out _))
                throw new ArgumentException("Invalid datetime format");

            // 表名安全验证
            if (string.IsNullOrWhiteSpace(tableName) || tableName.Any(c => !char.IsLetterOrDigit(c) && c != '_'))
                throw new ArgumentException("Invalid table name");

        }
    }
}
